//引入模块
var express = require('express')
var router = express.Router()
let mysql = require('../config/mysqlUtil.js')
let md5 = require('md5')
let JWT = require('../config/jwt.js').JWT


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource')
})

//获得req中的请求参数
function getParams(req) {
  //keys是body对象的属性名称数组，['username','password']
  let keys = Object.keys(req.body)
  return keys.length ? req.body : req.query
}

//登录函数
router.post('/login', function(req, res, next) {
  //1、解析请求参数
  let param = getParams(req)
  console.log(param)
  //2、连接数据库
  let connection = mysql.getConnection()
  //3、查询结果
  let sql = ' select * from smbms_user where username = ? and userPassword =? ; '
  console.log(sql)
  //查询参数
  let pass = md5(param.password || '123')
  let arr = [param.username, pass]
  console.log(arr)
  connection.query(sql, arr, function(err, rows) {
    //4、返回信息,是数组，如果没有查询到数据，返回[]
    let object = {}
    if (err) {
      console.log(err)
      object.data = null
      object.token = null
      object.meta = {
        msg: '服务器内部错误',
        status: 500
      }
    } else {
      console.log(rows)
      //没找这个人
      if (rows.length === 0) {
        object.data = null
        object.token = null
        object.meta = {
          msg: '错误的用户名或密码',
          status: 201
        }
      } else {
        //请求mysql数据成功，找到这个人，产生token
        let jwt = new JWT(param.username)
        let token = jwt.generateToken()
        object.data = rows
        object.token = token
        object.meta = {
          msg: '登录成功',
          status: 200
        }
      }
    }
    res.send(object)
  })
  //5、关闭连接
  connection.end()
})

//查询用户列表
router.get('/userList', function(req, res) {
  let param = getParams(req)
  let arr = []
  
  //准备sql和参数
  let sql = `SELECT
	                 u.*,
	                 r.rolename 
             FROM
	                 smbms_user u,
	                 smbms_role r 
             WHERE
                   u.userrole = r.id `
  if(param.username){
       arr.push('%'+ param.username + '%')
       sql+= 'and u.username like ?'
 }
 //获得连接
 let connection = mysql.getConnection()
 console.log(sql)
 console.log(arr)
  //执行查询
  connection.query(sql, arr, function(err, rows) {
    //返回数据
    let object = {}
    if (err) {
      console.log(err)
      object.data = null
      object.meta = {
        msg: '服务器内部错误',
        status: 500
      }
    } else {
      object.data = rows
      object.meta = {
        msg: '请求用户列表成功',
        status: 200
      }
    }
    res.send(object)
  })
  //关闭连接
  connection.end()
})

module.exports = router